package com.warrantyhotel.android.ui;

import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.CountryTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.LanguageTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.StateTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.UserInfo;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.service.UpdateNewsServise;
import com.warrantyhotel.android.util.DateUtis;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.JSONParser;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class SettingsActivity extends Activity implements Receiver, OnItemSelectedListener, AsyncQueryListener {
	private static final String TAG = SettingsActivity.class.getSimpleName();

	private DetachableResultReceiver receiver;
	private static SharedPreferences prefs;

	private NotifyingAsyncQueryHandler mHandler;

	private LinearLayout llSettingsItemsUserDetail;
	private LinearLayout llSettingsItemsPushNotif;
	private LinearLayout llSettingsPersonalInfo;
	private LinearLayout llChangePass;

	private EditText firstName;
	private EditText lastName;
	private EditText addressStreet;
	private EditText addressPostalCode;
	private EditText addressCity;
	private Spinner spnAddresCountrySpinner;
	private Spinner spnAddresStateSpinner;
	private Button birthDate;
	private Spinner spnGenderSpinner;
	private String country = null;
	private boolean isCountrySelected = false;
	private static final String FAKE_ID = "AAA";
	private Boolean gender = null;
	private int stateId = 0;
	private boolean isLanguageSelect = false;
	private int languageID = -1;
	private TextView txtMobilePrefix;
	private TextView txtPhonePrefix;
	private EditText edtPhone;
	private EditText edtMobile;
	private EditText oldPass;
	private EditText newPass;
	private EditText confirmPass;
	// private EditText changeEmail;

	private SimpleCursorAdapter countriesAdapter;
	private SimpleCursorAdapter stateAdapter;
	private ArrayAdapter<CharSequence> adapterGender;

	private Spinner spnLanguageSpinner;
	private SimpleCursorAdapter languageAdapter;

	private CheckBox chkNewMessage;
	private CheckBox chkNewsNotify;
	private Calendar calendar;
	private ProgressDialog progress;

	private static int count = 0;
	private static final int DATE_DIALOG_ID = 10;
	private static final int ACCOUNT_ID = 11;
	private String accountId = null;

	private boolean isGenderSelected = false;
	private int countryCountChose = 0;

	// private Cursor countryCursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);

		accountId = getIntent().getStringExtra(Keys._accountId);
		if (accountId != null)
			Log.v("asdasdas", accountId);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		coutryQueryRetrieving();
		languageQueryRetrieving();

		calendar = Calendar.getInstance();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		chkNewMessage = (CheckBox) findViewById(R.id.new_message_notify);
		chkNewsNotify = (CheckBox) findViewById(R.id.news_notify);

		chkNewMessage.setChecked(prefs.getBoolean(Keys.checkNewMessage, false));
		chkNewsNotify.setChecked(prefs.getBoolean(Keys.checkNews, false));

		chkNewsNotify.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				final Editor edit = prefs.edit();
				edit.putBoolean(Keys.checkNews, isChecked);
				edit.commit();

				Intent intent = new Intent(getApplicationContext(), UpdateNewsServise.class);
				if (isChecked) {
					startService(intent);
				} else {
					stopService(intent);
				}

			}
		});

		chkNewMessage.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				final Editor edit = prefs.edit();
				edit.putBoolean(Keys.checkNewMessage, isChecked);
				edit.commit();
			}
		});

		llSettingsItemsUserDetail = (LinearLayout) findViewById(R.id.settings_items);
		llSettingsItemsUserDetail.setVisibility(View.INVISIBLE);
		llSettingsItemsPushNotif = (LinearLayout) findViewById(R.id.push_notification_items);
		llSettingsPersonalInfo = (LinearLayout) findViewById(R.id.settings_personal_information_items);
		llChangePass = (LinearLayout) findViewById(R.id.change_pass_items);

		txtMobilePrefix = (TextView) findViewById(R.id.settings_address_mobile_prefix);
		txtPhonePrefix = (TextView) findViewById(R.id.settings_address_phone_prefix);
		edtPhone = (EditText) findViewById(R.id.settings_address_phone);
		edtMobile = (EditText) findViewById(R.id.settings_address_mobile);
		oldPass = (EditText) findViewById(R.id.old_pass);
		newPass = (EditText) findViewById(R.id.new_pass);
		confirmPass = (EditText) findViewById(R.id.new_pass_confirm);

		// changeEmail = (EditText) findViewById(R.id.change_email);

		firstName = (EditText) findViewById(R.id.settings_first_name);
		lastName = (EditText) findViewById(R.id.settings_second_name);
		addressStreet = (EditText) findViewById(R.id.settings_address_street);
		spnAddresCountrySpinner = (Spinner) findViewById(R.id.settings_country_spinner);
		spnAddresCountrySpinner.setOnItemSelectedListener(this);
		spnAddresStateSpinner = (Spinner) findViewById(R.id.settings_state_spinner);
		spnAddresStateSpinner.setOnItemSelectedListener(this);
		addressPostalCode = (EditText) findViewById(R.id.settings_zip_code);
		addressCity = (EditText) findViewById(R.id.settings_city);
		birthDate = (Button) findViewById(R.id.set_birth_date);
		birthDate.setTag(null);
		spnGenderSpinner = (Spinner) findViewById(R.id.setting_gender_spinner);
		adapterGender = ArrayAdapter.createFromResource(this, R.array.gender_array, android.R.layout.simple_spinner_item);

		adapterGender.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnGenderSpinner.setAdapter(adapterGender);
		spnGenderSpinner.setOnItemSelectedListener(this);

		spnLanguageSpinner = (Spinner) findViewById(R.id.settings_language_spinner);
		spnLanguageSpinner.setOnItemSelectedListener(this);

	}

	// query for retrieving phone prefix
	private void phonePrefixQueryRetrieving(String countryId) {
		String[] projectionCountry = { CountryTable._ID, CountryTable.NAME, CountryTable.COUNTRY_ID, CountryTable.PHONE_PREFIX };
		mHandler.startQuery(QueriesCodes.SELECT_PHONE_PREFIX, CountryTable.CONTENT_URI, projectionCountry,
				CountryTable.COUNTRY_ID.concat(" ='").concat(countryId).concat("'"), null, null);
	}

	// query for retrieving Language
	private void languageQueryRetrieving() {
		ContentValues values = new ContentValues();
		values.put(LanguageTable.LANGUAGE_ID, 0);
		values.put(LanguageTable.ENGLISH_NAME, getString(R.string.select_language));
		getContentResolver().insert(LanguageTable.CONTENT_URI, values);
		// query for retrieving Language
		String[] projectionLanguage = { LanguageTable._ID, LanguageTable.LANGUAGE_ID, LanguageTable.ENGLISH_NAME };
		mHandler.startQuery(QueriesCodes.SELECT_LANGUAGE_TABLE, LanguageTable.CONTENT_URI, projectionLanguage, null, null, LanguageTable.ENGLISH_NAME);
	}

	private void retrievingUserInfoOnce() {
		if (count < 1) {
			count++;
			Intent userInfoIntent = new Intent(Intent.ACTION_SYNC, StateTable.CONTENT_URI, this, UpdateIntentService.class);
			userInfoIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
			userInfoIntent.putExtra(Keys._accountId, accountId);
			userInfoIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_BY_ID);
			startService(userInfoIntent);
			progress = ProgressDialog.show(SettingsActivity.this, getApplicationContext().getString(R.string.loading),
					getApplicationContext().getString(R.string.please_wait), true, false);
		}
	}

	// query for retrieving Country
	private void coutryQueryRetrieving() {

		ContentValues values = new ContentValues();
		values.put(CountryTable.NAME_HACK, FAKE_ID);
		values.put(CountryTable.COUNTRY_ID, FAKE_ID);
		values.put(CountryTable.NAME, getString(R.string.select_country));
		getContentResolver().insert(CountryTable.CONTENT_URI, values);

		String[] projectionCountry = { CountryTable._ID, CountryTable.NAME, CountryTable.COUNTRY_ID };
		mHandler.startQuery(QueriesCodes.SELCET_COUNTRY_TABLE, CountryTable.CONTENT_URI, projectionCountry, null, null, CountryTable.NAME);
	}

	// query for retrieving State
	private void stateQueryRetrieving(String countryId) {

		String[] projectionState = { StateTable._ID, StateTable.STATE_NAME, StateTable.STATE_ID, StateTable.COUNTRY_ID };
		mHandler.startQuery(QueriesCodes.SELECT_STATE_TABLE, StateTable.CONTENT_URI, projectionState, StateTable.COUNTRY_ID.concat("='").concat(countryId)
				.concat("'"), null, null);
	}

	public void setBirthDate(View view) {
		showDialog(DATE_DIALOG_ID);
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			// do nothing
			break;
		case UpdateIntentService.STATUS_ERROR:
			if (null != progress)
				progress.dismiss();
			// finish();
			break;

		case UpdateIntentService.STATUS_FINISHED:
			if (null != progress)
				progress.dismiss();

			if (resultData.containsKey(Keys.userInfo)) {
				final UserInfo userInfo = resultData.getParcelable(Keys.userInfo);
				if (userInfo.getFirstName() != null) {
					firstName.setText(userInfo.getFirstName());
					// Log.v("userInfo.getFirstName()",
					// userInfo.getFirstName());
				}
				if (userInfo.getLastName() != null)
					lastName.setText(userInfo.getLastName());
				if (userInfo.getAddressStreet() != null)
					addressStreet.setText(userInfo.getAddressStreet());
				if (userInfo.getAddressCountryId() != null) {
					Cursor countryCursor = countriesAdapter.getCursor();
					if (countryCursor.moveToFirst()) {
						while (!userInfo.getAddressCountryId().equals(countryCursor.getString(countryCursor.getColumnIndex(CountryTable.COUNTRY_ID)))) {
							if (!countryCursor.moveToNext())
								break;
						}
						try {
							spnAddresCountrySpinner.setSelection(countryCursor.getPosition());
						} catch (Exception e) {
							e.printStackTrace();
						}

						try {
							if (userInfo.getAddressCountryId() != null) {
								executeRequest(userInfo.getAddressCountryId(), new ResponseHandler() {
									public void handleResponse(Cursor cursor) {
										if (cursor.moveToFirst()) {
											try {
												while (!userInfo.getAddressStateId().equals(cursor.getString(cursor.getColumnIndex(StateTable.STATE_ID)))) {
													if (!cursor.moveToNext())
														break;
												}
												spnAddresStateSpinner.setSelection(cursor.getPosition());
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								});
							}
						} catch (IOException e) {
							android.util.Log.e(TAG, "Could not find state: " + e);
						}
					}
				}

				if (userInfo.getLanguage() != null) {
					Cursor languageCursor = languageAdapter.getCursor();
					if (languageCursor.moveToFirst()) {
						while (!userInfo.getLanguage().equals(languageCursor.getString(languageCursor.getColumnIndex(LanguageTable.LANGUAGE_ID)))) {
							if (!languageCursor.moveToNext())
								break;
						}
						spnLanguageSpinner.setSelection(languageCursor.getPosition());
					}
				}

				if (userInfo.getAddressStreet() != null)
					addressStreet.setText(userInfo.getAddressStreet());
				if (userInfo.getAddressCity() != null)
					addressCity.setText(userInfo.getAddressCity());
				if (userInfo.getAddressPostalCode() != null)
					addressPostalCode.setText(userInfo.getAddressPostalCode());
				if (userInfo.getBirthDate() != null) {
					birthDate.setText(DateUtis.parseDateFromMilliseconds(userInfo.getBirthDate()));
				}

				int genderPosition = 0;
				if (userInfo.getGender() == null)
					genderPosition = 0;
				else if (userInfo.getGender())
					genderPosition = 1;
				else if (!userInfo.getGender())
					genderPosition = 2;
				spnGenderSpinner.setSelection(genderPosition);

				if (userInfo.getPhone() != null)
					edtPhone.setText(userInfo.getPhone());
				if (userInfo.getMobile() != null)
					edtMobile.setText(userInfo.getMobile());

				llSettingsItemsUserDetail.setVisibility(View.GONE);

			}

			if (resultData.containsKey(Keys.isUserInfoSaved)) {
				if (resultData.containsKey(Keys.isUserInfoSaved)) {
					final Editor edit = prefs.edit();
					String first = firstName.getText().toString().trim();
					String last = lastName.getText().toString().trim();
					edit.putString(Keys._firstName, TextUtils.isEmpty(first) ? null : first);
					edit.putString(Keys._lastName, TextUtils.isEmpty(last) ? null : last);
					edit.commit();
				}

				String message = resultData.containsKey(Keys.isUserInfoSaved) ? getString(R.string.account_was_updated)
						: getString(R.string.account_was_not_updated);
				ToastUtil.showText(getApplicationContext(), message);
			}
			break;
		}
	}

	public void changeVisibility(View view) {
		View llTab = null;
		ImageView imageView = null;
		switch (view.getId()) {
		case R.id.settings_items_button:
			llTab = llSettingsItemsUserDetail;
			imageView = (ImageView) findViewById(R.id.sett_swither_image_1);
			break;
		case R.id.push_notification_items_button:
			llTab = llSettingsItemsPushNotif;
			imageView = (ImageView) findViewById(R.id.sett_swither_image_3);
			break;
		case R.id.settings_personal_information_items_button:
			llTab = llSettingsPersonalInfo;
			imageView = (ImageView) findViewById(R.id.sett_swither_image_2);
			break;
		case R.id.change_pass:
			llTab = llChangePass;
			imageView = (ImageView) findViewById(R.id.sett_swither_image_4);
			break;

		default:
			break;
		}
		if (null != llTab) {
			llTab.setVisibility(convertVisibility(llTab.getVisibility()));
			imageView.setImageResource((llTab.getVisibility() == View.VISIBLE) ? R.drawable.arr_down : R.drawable.arr_right);
		}
	}

	/**
	 * Convert visibility from GONE to VISIBLE and opposite
	 */
	private int convertVisibility(int visibility) {
		return (visibility == View.VISIBLE) ? View.GONE : View.VISIBLE;
	}

	public void onSave(View view) {

		JSONObject jObj = new JSONObject();
		try {

			jObj.put(Keys._accountId, prefs.getString(Keys._accountId, null));
			jObj.put(Keys._tokenId, prefs.getString(Keys._tokenId, null));

			if (chechValue(firstName))
				jObj.put(JSONParser.FIRST_NAME, firstName.getText().toString().trim());
			if (chechValue(lastName))
				jObj.put(JSONParser.LAST_NAME, lastName.getText().toString().trim());
			if (chechValue(addressStreet))
				jObj.put(JSONParser.ADDRESS_STREET, addressStreet.getText().toString().trim());

			if (isCountrySelected) {
				jObj.put(JSONParser.ADDRESS_COUNTRY_ID, (FAKE_ID.equals(country)) ? JSONObject.NULL : country);
			}

			if (0 != stateId) {
				jObj.put(JSONParser.ADDRESS_STATE_ID, stateId);
			}

			if (chechValue(addressPostalCode))
				jObj.put(JSONParser.ADDRESS_POSTAL_CODE, addressPostalCode.getText().toString().trim());
			if (chechValue(addressCity))
				jObj.put(JSONParser.ADDRESS_CITY, addressCity.getText().toString().trim());
			if (birthDate.getTag() != null)
				jObj.put(JSONParser.BIRTH_DATE, DateUtis.decodeDate((Long) birthDate.getTag()));

			if (isGenderSelected)
				jObj.put(JSONParser.GENDER, (gender == null) ? JSONObject.NULL : gender);


			if (isLanguageSelect)
				jObj.put(JSONParser.PREFERRED_LANGUAGE_ID, (languageID == 0) ? JSONObject.NULL : String.valueOf(languageID));

			if (chechValue(edtPhone))
				jObj.put(JSONParser.PHONE, edtPhone.getText().toString().trim());

			if (chechValue(edtMobile))
				jObj.put(JSONParser.MOBILE_PHONE, edtMobile.getText().toString().trim());

			jObj.put(JSONParser.MOBILE_PHONE_PREFIX, txtMobilePrefix.getText().toString().trim());
			jObj.put(JSONParser.PHONE_PREFIX, txtPhonePrefix.getText().toString().trim());

			String oldPassword = oldPass.getText().toString().trim();
			String newPassword = newPass.getText().toString().trim();
			String confPass = confirmPass.getText().toString().trim();

			if ((!TextUtils.isEmpty(oldPassword) && TextUtils.isEmpty(newPassword)) || (TextUtils.isEmpty(oldPassword) && !TextUtils.isEmpty(newPassword))) {
				ToastUtil.showText(getApplicationContext(), getString(R.string.one_of_pass));
				return;
			} else if (!TextUtils.isEmpty(newPassword) && !TextUtils.isEmpty(oldPassword)) {
				if (!oldPassword.equals(prefs.getString(Keys._password, ""))) {
					ToastUtil.showText(getApplicationContext(), getString(R.string.old_pass_is_incorrect));
					return;
				} else if (!newPassword.equals(confPass)) {
					ToastUtil.showText(getApplicationContext(), getString(R.string.pass_are_differ));
					return;
				} else {
					jObj.put(Keys._MD5Pass, DigestUtils.md5Hex(newPassword));
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		Intent userInfoIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		userInfoIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		userInfoIntent.putExtra(Keys.userInfoJson, jObj.toString());

		Log.e("jObj.toString()", jObj.toString());
		System.out.print(jObj.toString());

		userInfoIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_SAVE);
		startService(userInfoIntent);

	}

	private boolean chechValue(EditText field) {
		return (null != field && !TextUtils.isEmpty(field.getText().toString().trim()));
	}

	@Override
	public void onItemSelected(AdapterView<?> adapterView, View arg1, int position, long id) {
		if (adapterView.getAdapter().equals(countriesAdapter)) {
			String countryId = "";
			Cursor mCursor = countriesAdapter.getCursor();
			if (null != mCursor) {
				if (mCursor.moveToPosition(position)) {
					countryCountChose++;
					if (countryCountChose > 1) {
						countryId = mCursor.getString(mCursor.getColumnIndex(CountryTable.COUNTRY_ID));
						country = countryId;
						if (FAKE_ID.equals(country)) {
							stateId = 0;
						}
						isCountrySelected = true;
					}
					System.out.println(countryId);
				}
			}
			// query for retrieving states
			stateQueryRetrieving(countryId);

			// query for retrieving phone prefix
			phonePrefixQueryRetrieving(countryId);

		} else if (adapterView.getAdapter().equals(stateAdapter)) {
			Cursor mCursor = stateAdapter.getCursor();

			if (null != mCursor) {
				if (mCursor.moveToPosition(position)) {
					stateId = mCursor.getInt(mCursor.getColumnIndex(StateTable.STATE_ID));
				}
				Log.i("stateId", " " + stateId);
			}
			// retrievingUserInfoOnce();
		} else if (adapterView.getAdapter().equals(adapterGender)) {
			switch (position) {
			case 0:
				isGenderSelected = true;
				gender = null;
				break;
			case 1:
				isGenderSelected = true;
				gender = Boolean.TRUE;
				break;
			case 2:
				isGenderSelected = true;
				gender = Boolean.FALSE;
				break;
			default:
				break;
			}

		} else if (adapterView.getAdapter().equals(languageAdapter)) {

			Cursor mCursor = languageAdapter.getCursor();
			if (null != mCursor) {
				isLanguageSelect = true;
				if (mCursor.moveToPosition(position)) {
					languageID = mCursor.getInt(mCursor.getColumnIndex(LanguageTable.LANGUAGE_ID));
					Log.i(TAG, " " + languageID);
				}
			}
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.SELCET_COUNTRY_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				// countryCursor = cursor;
				if (null == countriesAdapter) {

					// // if db is empty
					// if (cursor.getCount() == 0)
					// progress = ProgressDialog.show(this,
					// getString(R.string.loading),
					// getString(R.string.please_wait), true, false);

					countriesAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { CountryTable.NAME },
							new int[] { android.R.id.text1 });
					spnAddresCountrySpinner.setAdapter(countriesAdapter);
					countryCountChose = 0;
					countriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					countriesAdapter.changeCursor(cursor);
					countriesAdapter.notifyDataSetChanged();
				}
				// retrievingUserInfo();
			}
			break;
		case QueriesCodes.SELECT_STATE_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				// if (cursor.getCount() == 0)
				// retrievingUserInfoOnce();
				boolean state = (cursor.getCount() == 0) ? false : true;
				spnAddresStateSpinner.setEnabled(state);
				if (null == stateAdapter) {
					stateAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { StateTable.STATE_NAME },
							new int[] { android.R.id.text1 });
					spnAddresStateSpinner.setAdapter(stateAdapter);
					stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					stateAdapter.changeCursor(cursor);
					stateAdapter.notifyDataSetChanged();
				}
			}
			retrievingUserInfoOnce();
			break;
		case QueriesCodes.SELECT_LANGUAGE_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (null == languageAdapter) {
					languageAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { LanguageTable.ENGLISH_NAME },
							new int[] { android.R.id.text1 });
					spnLanguageSpinner.setAdapter(languageAdapter);
					languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					languageAdapter.changeCursor(cursor);
					languageAdapter.notifyDataSetChanged();
				}

			}
			break;
		case QueriesCodes.SELECT_PHONE_PREFIX:
			if (cursor != null) {
				String phonePrefix = "";
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					phonePrefix = cursor.getString(cursor.getColumnIndex(CountryTable.PHONE_PREFIX));
				}
				cursor.close();
				txtMobilePrefix.setText(phonePrefix);
				txtPhonePrefix.setText(phonePrefix);
			}
			break;
		// case QueriesCodes.SELCET_COUNTRY_TABLE_BY_ID:
		// break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		count = 0;
	}

	private static interface ResponseHandler {
		public void handleResponse(Cursor cursor);
	}

	private void executeRequest(String counrtyId, ResponseHandler handler) throws IOException {
		String[] projectionState = { StateTable._ID, StateTable.STATE_NAME, StateTable.STATE_ID, StateTable.COUNTRY_ID };

		Cursor cursor = managedQuery(StateTable.CONTENT_URI, projectionState, StateTable.COUNTRY_ID.concat("='").concat(counrtyId).concat("'"), null, null);

		if (null == stateAdapter) {
			stateAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { StateTable.STATE_NAME },
					new int[] { android.R.id.text1 });
			spnAddresStateSpinner.setAdapter(stateAdapter);
			stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		} else {
			stateAdapter.changeCursor(cursor);
			stateAdapter.notifyDataSetChanged();
		}

		handler.handleResponse(cursor);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// return new DatePickerDialog(this, mDateSetListener,
			// calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
			// calendar.get(Calendar.DAY_OF_MONTH));
			return new DatePickerDialog(this, mDateSetListener, 1980, 0, 1);
		}
		return null;
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			if (calendar.getTimeInMillis() > System.currentTimeMillis()) {
				ToastUtil.showText(getApplicationContext(), getString(R.string.invalid_date));
			} else {
				birthDate.setText(DateFormat.format(Keys.dateFormat, calendar));
				birthDate.setTag(calendar.getTimeInMillis());
			}

		}
	};

	public void showDialogChangePass(View view) {
		Intent intent = new Intent(SettingsActivity.this, ChanageEmailActivity.class);
		startActivityForResult(intent, ACCOUNT_ID);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case ACCOUNT_ID:
			if (data != null && data.hasExtra(Keys._accountId)) {
				accountId = data.getStringExtra(Keys._accountId);

				finish();

				count = 0;

				Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
				intent.putExtra(Keys._accountId, accountId);
				startActivity(intent);

				break;
			}
			break;

		default:
			break;
		}

	}
}
